package org.vectrics.recruiter.document;

import java.io.FileInputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Category;
import org.vectrics.SystemException;
import org.vectrics.VectricsException;
import org.vectrics.recruiter.RecruitServiceLocator;
import org.vectrics.recruiter.config.RecruitConfig;
import org.vectrics.recruiter.user.RecruitUserManager;
import org.vectrics.recruiter.user.Resume;
import org.vectrics.struts.DocumentResponse;
import org.vectrics.struts.Request;
import org.vectrics.user.Person;

public class DocumentRequestManager {
    private static Category log = Category.getInstance(DocumentRequestManager.class);

    public void service(Request request, DocumentResponse documentResponse, Person authPerson) {
        try {
            log.info("service() - handling request for document");

            log.debug("Setting content type");
            documentResponse.setContentType("application/word");
            String resumeId = request.getParameter("resumeId");
            String documentId = request.getParameter("documentId");

            String fileAndPath = null;
            if (documentId != null) {
                CandidateDocument document = RecruitServiceLocator.getRecruitUserService().findCandidateDocument(
                        new Long(documentId));
                fileAndPath = RecruitConfig.getRecruitInstance().getCandidateDocumentPath(document.getDomain()) + "/"
                        + document.getSavedFileName();
            } else if (resumeId != null) {
                RecruitUserManager recruitUserMgr = new RecruitUserManager();
                Resume resume = recruitUserMgr.findResume(new Long(resumeId));

                boolean personOwnsResume = resume.getCandidateInfo().getPerson().getId().equals(authPerson.getId());
                boolean personCanViewResumes = authPerson.hasDomainOrGlobalRole("resume.view", resume.getDomain());
                log.debug("Person owns resume = " + personOwnsResume);
                log.debug("Person can view resumes = " + personCanViewResumes);

                fileAndPath = RecruitConfig.getRecruitInstance().getCandidateDocumentPath(resume.getDomain()) + "/"
                        + resume.getDocument().getSavedFileName();
            } else {
                log.error("No resumeId or attachment id was set");
                throw new VectricsException("No resumeId or attachment id was set");
            }

            log.debug("Writing bytes to response");
            FileInputStream fileStream = new FileInputStream(fileAndPath);

            StringBuffer content = new StringBuffer();
            int word = 0;
            boolean done = false;
            while (!done) {
                word = fileStream.read();
                if (word >= 0) {
                    content.append((char) word);
                } else {
                    done = true;
                }
            }
            documentResponse.setContent(content);
        } catch (Exception ve) {
            log.error("VectricsException in service()", ve);
            throw new SystemException("VectricsException in service()", ve);
        }
    }

    private void savePathToSession(HttpServletRequest request) {
        String formPath = request.getRequestURI();
        log.info("formPath = " + formPath);
        HttpSession session = request.getSession();
        session.setAttribute("form-path", formPath);
        session.setAttribute("context-path", request.getContextPath());

        log.info("ContextPath = " + session.getAttribute("context-path"));
    }

}